#define  _CRT_SECURE_NO_WARNINGS
#include <vector>
#include <iostream>
using namespace std;
#include <string>
#include <set>
#include <functional>
vector<vector<int>> arr;
int n, k1;
set<string> set1;
string path;
int dy[9] = {0, 1, 1, 1, 0, -1, -1, -1, 0 };
int dx[9] = {0, -1, 0, 1, 1, 1, 0, -1, -1 };

bool vis[10][10];
void dfs(int i, int j, int cur, int sum)
{
	if (sum == n * n && i == n - 1 && j == n - 1)
	{
		set1.insert(path);
		return;
	}
	for (int k = 1; k <= 8; k++)
	{
		int x = i + dx[k], y = j + dy[k];
		if (x >= 0 && x < n && y >= 0 && y < n && !vis[x][y] && arr[x][y] == cur)
		{
			if (k == 1 && vis[i + 1][j] && vis[i][j - 1])continue;
			if (k == 3 && vis[i + 1][j] && vis[i][j + 1])continue;
			if (k == 5 && vis[i][j + 1] && vis[i - 1][j])continue;
			if (k == 7 && vis[i - 1][j] && vis[i][j - 1])continue;

			vis[x][y] = true;
			path += k + '0';
			dfs(x, y, (cur + 1) % k1, sum + 1);
			vis[x][y] = false;
			path.pop_back();
		}
	}
}
int main()
{
	cin >> n >> k1;
	arr.resize(n, vector<int>(n));
	for (int i = 0; i < n; i++)
		for (int j = 0; j < n; j++)
			cin >> arr[i][j];
	if (arr[0][0])
	{
		cout << -1;
		return 0;
	}
	vis[0][0] = true;
	dfs(0, 0, 1 % k1, 1);
	if (set1.size() == 0)
		cout << -1;
	else cout << *set1.begin();
	return 0;
}
